#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 4e5 + 5;

int n, k;
int a[N], l[N], r[N];
list<int> q[N];
set<pii> mn, mx;
ll sumd;
ll suml;
void init() {
  sumd = suml = 0;
  mn.clear(), mx.clear();
  rep(i, 1, k) q[i].clear();
}
void insert(pii x) {
  if (x.first < mx.begin()->first) {
    mn.insert(x);
    sumd += x.first;
    if (mn.size() > (k + 1) / 2) {
      pii y = *mn.rbegin();
      mn.erase(y);
      mx.insert(y);
      sumd -= y.first;
    }
  } else {
    mx.insert(x);
    if (mx.size() > k / 2) {
      pii y = *mx.begin();
      mx.erase(y);
      mn.insert(y);
      sumd += y.first;
    }
  }
}
void remove(pii x) {
  if (mn.count(x)) {
    mn.erase(x);
    sumd -= x.first;
  } else {
    mx.erase(x);
  }
}
void solve() {
  cin >> n >> k;
  rep(i, 1, n) cin >> a[i];
  init();
  ll ans = 1e18;
  rep(j, 1, k) l[j] = -n;
  suml = 1ll * k * (-n);
  rep(j, 1, n) q[a[j]].push_back(j);
  rep(j, 1, k) q[j].push_back(n * 2);
  rep(j, 1, k) {
    int x = l[j];
    int y = q[j].front();
    insert(pii(y + x, j));
  }
  rep(i, 1, n) {
    // i - > left
    if (i > 1) {
      // delete i - 1
      int x = a[i - 1];
      remove(pii(2 * i - 2, x));
      q[x].pop_front();
      insert(pii(q[x].front() + i - 1, x));
    }
    int x = a[i];
    int pre = l[x];
    suml -= pre;
    remove(pii(i + pre, x));
    l[x] = i;
    suml += i;
    insert(pii(i * 2, x));
    ans = min(ans, sumd - suml - (k % 2 ? i : 0));
  }
  rep(i, 1, k) ans -= abs(i - (k + 1) / 2);
  cout << ans << endl;
}

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}